package com.wang.tool.mybatis;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.EnumTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 枚举适配器类
 * db读写枚举像字符串存取一样，无需任何配置，枚举实现PoEnum 或者实现 getCode函数
 * @see PoEnum
 * @Author wangshaopeng
 * @Date 2020/8/24
 */
public class AutoEnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

    /**
     * 所有常量
     */
    private final BaseTypeHandler<E> delegate;


    /**
     * mybatis在3.*版本后支持设置通用枚举的类型转换器
     * 如果是之前,需要,获取configuration对象使用里面的typeHandlerRegistry手动注册
     * 手动注册优先级高
     * 函数org.apache.ibatis.type.TypeHandlerRegistry#getJdbcHandlerMap(java.lang.reflect.Type)这里直接取class参数的构造器
     * 所以不留默认构造
     *
     * @param type
     */
    public AutoEnumTypeHandler(Class<E> type) {
        if (!Enum.class.isAssignableFrom(type)) {
            throw new IllegalArgumentException("该handler仅支持枚举类型!");
        }
        if (PoEnum.class.isAssignableFrom(type)) {
            delegate = new PoEnumTypeHandler<>(type);
        } else {
            GetCodeEnumTypeHandler<E> getCodeEnumTypeHandler = null;
            try {
                getCodeEnumTypeHandler = new GetCodeEnumTypeHandler<>(type);
            } catch (Throwable ignore) {
            }
            if (getCodeEnumTypeHandler == null) {
                delegate = new EnumTypeHandler<>(type);
            } else {
                delegate = getCodeEnumTypeHandler;
            }
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        delegate.setNonNullParameter(ps, i, parameter, jdbcType);
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return delegate.getNullableResult(rs, columnName);
    }


    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return delegate.getNullableResult(rs, columnIndex);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return delegate.getNullableResult(cs, columnIndex);
    }

}
